<?php
namespace Wechat\Controller;

use Wechat\Controller\AppController;
use Cake\Event\Event;
use Psr\Log\LogLevel;

/**
 * 微信接入接口
 *
 * @author Wenchaojun <343169893@qq.com>
 * @property \Wechat\Controller\Component\WechatComponent $Wechat
 * @property \Wechat\Controller\Component\WxBizMsgCryptComponent $WxBizMsgCrypt
 */
class JoinsController extends AppController
{

    var $allowedActions = [
        'index',
        'sharetoken'
    ];

    public function beforeFilter(Event $event)
    {
        $this->Cookie->setConfig("domain", "icoin.cjblog.org");
        // 不要调用父级的过滤器
        $this->Auth->allow();
    }

    /**
     *
     * @link http://icoin.cjblog.org/wechat/joins/sharetoken/10000.json
     *      
     *      
     */
    public function sharetoken($id)
    {
        $this->loadComponent('Wechat.Wechat', [
            'id' => $id
        ]);
        // $prox = $this->request->is("ssl") ? "https" : "http";
        // header('Access-Control-Allow-Origin: ' . $prox . '://icoin.cjblog.org');
        $signPackage = $this->Wechat->GetSignPackage($this->request->getData("url"));
        // unset($signPackage["rawString"]);
        $this->set("data", $signPackage);
        $this->set("_serialize", "data");
    }

    /**
     * 验证接入/反馈微信转发请求
     *
     * @link http://icoin.cjblog.org/wechat/joins/index/1
     */
    public function index($id)
    {
        $this->viewBuilder()->setLayout("");
        $this->loadComponent('Wechat.Wechat', [
            'id' => $id
        ]);
        $data = "";
        // 2种情况，1验证服务器，2自动回复，都需要验证请求参数的合法性
        $timestamp = $this->request->getQuery("timestamp");
        $nonce = $this->request->getQuery("nonce");
        $isEt = $this->request->getQuery("encrypt_type", "") == "aes";
        if ($this->Wechat->valid($this->request->getQuery("signature"), $timestamp, $nonce)) {
            $echostr = $this->request->getQuery("echostr");
            if (! empty($echostr)) {
                // 验证服务器
                $data = $echostr;
            } else {
                $this->loadComponent('Wechat.WxBizMsgCrypt', $this->Wechat->getConfig());
                // 回复消息
                if ($isEt) {
                    // 加密啦 https://blog.csdn.net/zhongdajiajiao/article/details/51195536
                    $content = $this->WxBizMsgCrypt->decryptMsg($this->request->getQuery("msg_signature"), $timestamp, $nonce, $this->request->getData("xml"));
                    $this->log("加密信息", LogLevel::INFO);
                } else {
                    $content = $this->request->getData("xml");
                }
                // 处理消息
                $data = $this->responseMsg($content);
                if ($isEt) {
                    // 返回给用户：转换成xml 再加密encryptMsg($text, $timeStamp, $nonce, $encryptMsg);
                    $data = $this->WxBizMsgCrypt->encryptMsg($data);
                }
            }
        }
        $this->set("data", $data);
    }

    // 响应消息
    private function responseMsg($postObj)
    {
        $result = "";
        if (! empty($postObj)) {
            switch ($postObj->MsgType) {
                case "event":
                    $result = $this->receiveEvent($postObj);
                    break;
                case "text":
                    $result = $this->receiveText($postObj);
                    break;
                case "image":
                    $result = $this->receiveImage($postObj);
                    break;
                case "location":
                    $result = $this->receiveLocation($postObj);
                    break;
                case "voice":
                    $result = $this->receiveVoice($postObj);
                    break;
                case "video":
                    $result = $this->receiveVideo($postObj);
                    break;
                case "link":
                    $result = $this->receiveLink($postObj);
                    break;
                default:
                    $result = "unknown msg type";
                    break;
            }
        }
        return $result;
    }

    // 接收文本消息
    private function receiveText($object)
    {
        $this->log($object, LogLevel::INFO);
        switch ($object->Content) {
            case "文本":
                $content = "这是个文本消息";
                break;
            case "我的信息":
                $content = $object->FromUserName;
                break;
            case "提现":
                $content = "<a href='https://weixin.mofing.com/tixian.html'>点击进入提现</a>";
                break;
            case "获取token":
                $this->log("获取token", LogLevel::INFO);
                $content = $this->Wechat->getAccessToken(true);
                $this->log($content, LogLevel::INFO);
                break;
            default:
                $word = $object->Content;
                $content = $word;
                break;
        }
        
        return $this->transmitResult($object, $content);
    }

    public function test()
    {
        $text = $this->request->getData("text");
        $data = $this->convertGoods($text);
        $this->set("data", $data);
    }

    /**
     * 转换产品
     *
     * @param string $word            
     */
    private function convertGoods($word)
    {
        // 判断是淘宝/京东/亚马逊
        $retailer = $this->loadComponent("Retailer.Taobao");
        $data = $retailer->getGoodsInfo($word);
        
        
        
        return $data;
    }

    private function transmitResult($object, $content)
    {
        if (is_array($content)) {
            if (isset($content[0]['PicUrl'])) {
                $result = $this->WxBizMsgCrypt->transmitNews($object, $content);
            } else if (isset($content['video'])) {
                $result = $this->WxBizMsgCrypt->transmitVideo($object, $content);
            } else if (isset($content['MusicUrl'])) {
                $result = $this->WxBizMsgCrypt->transmitMusic($object, $content);
            }
        } else {
            $result = $this->WxBizMsgCrypt->transmitText($object, $content);
        }
        return $result;
    }

    // 接收事件消息
    private function receiveEvent($object)
    {
        $content = "";
        switch ($object->Event) {
            case "subscribe":
                // $content = "欢迎关注木丰众易 ";
                $content = $this->choujiang();
                break;
            case "unsubscribe":
                $content = "取消关注";
                break;
            case "SCAN":
                $content = "扫描场景 " . $object->EventKey;
                break;
            case "CLICK":
                switch ($object->EventKey) {
                    case "COMPANY":
                        $content = "木丰众易。";
                        break;
                    case "mofing_activity":
                        $content = "木丰众易活动";
                        break;
                    case "mofing_kouling_activity":
                        $content = "阿宝领口令赢大奖活动暂未开启，敬请期待！";
                        break;
                    case "mofing_member_activity":
                        $content = "阿宝会员暂未开启，敬请期待！";
                        break;
                    default:
                        $content = "点击菜单：" . $object->EventKey;
                        break;
                }
                break;
            case "LOCATION":
                $content = "上传位置：纬度 " . $object->Latitude . ";经度 " . $object->Longitude;
                break;
            case "VIEW":
                $content = "跳转链接 " . $object->EventKey;
                break;
            default:
                $content = "receive a new event: " . $object->Event;
                break;
        }
        return $this->transmitResult($object, $content);
    }

    // 接收图片消息
    private function receiveImage($object)
    {
        $content = array(
            "MediaId" => $object->MediaId
        );
        $result = $this->WxBizMsgCrypt->transmitImage($object, $content);
        return $result;
    }

    // 接收位置消息
    private function receiveLocation($object)
    {
        $content = "你发送的是位置，纬度为：" . $object->Location_X . "；经度为：" . $object->Location_Y . "；缩放级别为：" . $object->Scale . "；位置为：" . $object->Label;
        $result = $this->WxBizMsgCrypt->transmitText($object, $content);
        return $result;
    }

    // 接收语音消息
    private function receiveVoice($object)
    {
        if (isset($object->Recognition) && ! empty($object->Recognition)) {
            $content = "你刚才说的是：" . $object->Recognition;
            $result = $this->WxBizMsgCrypt->transmitText($object, $content);
        } else {
            $content = array(
                "MediaId" => $object->MediaId
            );
            $result = $this->WxBizMsgCrypt->transmitVoice($object, $content);
        }
        
        return $result;
    }

    // 接收视频消息
    private function receiveVideo($object)
    {
        $content = array(
            "MediaId" => $object->MediaId,
            "ThumbMediaId" => $object->ThumbMediaId,
            "Title" => "",
            "Description" => ""
        );
        $result = $this->WxBizMsgCrypt->transmitVideo($object, $content);
        return $result;
    }

    // 接收链接消息
    private function receiveLink($object)
    {
        $content = "你发送的是链接，标题为：" . $object->Title . "；内容为：" . $object->Description . "；链接地址为：" . $object->Url;
        $result = $this->WxBizMsgCrypt->transmitText($object, $content);
        return $result;
    }
}
